<template>
  <div class="coupon-manage-container">
    <!-- 页面标题 + 操作栏（若依风格：标题+搜索+功能按钮） -->
    <div class="page-header">
      <h2 class="page-title">优惠券管理</h2>
      <div class="operation-bar">
        <!-- 搜索框：支持名称/编号搜索 -->
        <el-input
            v-model="searchValue"
            placeholder="请输入优惠券名称或编号搜索"
            class="search-input"
            clearable
            @keyup.enter="handleSearch"
            style="width: 300px; height: 40px;"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" style="height: 100%; border-left: none;"/>
          </template>
        </el-input>

        <!-- 功能按钮：新增+批量导入（若依常用操作） -->
        <el-button
            type="primary"
            @click="showAddDialog = true"
            icon="el-icon-plus"
            style="height: 40px; margin-left: 10px;"
        >
          新增优惠券
        </el-button>
        <el-button
            type="success"
            @click="showBatchImportDialog = true"
            icon="el-icon-upload2"
            style="height: 40px; margin-left: 10px;"
        >
          批量导入
        </el-button>
      </div>
    </div>

    <!-- 优惠券表格（若依风格：条纹+边框+表头灰底） -->
    <el-card class="table-card">
      <!-- 加载骨架屏 -->
      <el-skeleton v-if="loading" row-count="5" :columns="8" border></el-skeleton>

      <el-table
          v-else
          :data="filteredCouponList"
          style="width: 100%"
          stripe
          border
          :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 500 }"
          :cell-style="{ color: '#666' }"
          @row-click="handleRowClick"
          size="mini"
      >
        <!-- 序号列 -->
        <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
        <!-- 优惠券编号（唯一标识） -->
        <el-table-column prop="couponNo" label="优惠券编号" width="180" align="center"></el-table-column>
        <!-- 优惠券名称 -->
        <el-table-column prop="name" label="优惠券名称" width="200" align="center"></el-table-column>
        <!-- 优惠券类型（字典转换：1->饮品兑换券等） -->
        <el-table-column label="优惠券类型" width="140" align="center">
          <template #default="{ row }">
            <el-tag :type="getCouponTypeTagType(row.type)">
              {{ getCouponTypeName(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 优惠值（区分满减/折扣） -->
        <el-table-column label="优惠值" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.type === 2 ? `¥${row.value}` : (row.type === 3 ? `${row.value}折` : '免费兑换') }}</span>
          </template>
        </el-table-column>
        <!-- 最低消费 -->
        <el-table-column label="最低消费" width="120" align="center">
          <template #default="{ row }">
            <span>{{ row.minSpend === 0 ? '无门槛' : `¥${row.minSpend}` }}</span>
          </template>
        </el-table-column>
        <!-- 有效期 -->
        <el-table-column label="有效期" min-width="220" align="center">
          <template #default="{ row }">
                        <span>{{ formatDate(row.validStartTime) }} - {{ formatDate(row.validEndTime) }}</span>
          </template>
        </el-table-column>
        <!-- 库存状态 -->
        <el-table-column label="库存状态" width="140" align="center">
          <template #default="{ row }">
            <el-progress :percentage="(1 - row.remainingCount/row.totalCount) * 100" size="small"
                         :status="row.remainingCount === 0 ? 'exception' : 'success'"/>
            <div class="stock-text">{{ row.remainingCount }}/{{ row.totalCount }}</div>
          </template>
        </el-table-column>
        <!-- 状态（字典转换：0->已下架等） -->
        <el-table-column label="状态" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : (row.status === 2 ? 'warning' : 'danger')">
              {{ getCouponStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 操作列（编辑+删除） -->
        <el-table-column min-width="180" label="操作" align="center">
          <template #default="{ row }">
            <el-button
                type="text"
                color="#409eff"
                size="small"
                @click.stop="editCoupon(row)"
                :disabled="row.status === 2"
            >
              编辑
            </el-button>
            <el-button
                type="text"
                color="#f56c6c"
                size="small"
                @click.stop="handleDeleteConfirm(row.id)"
                :disabled="row.totalCount > row.remainingCount"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空数据提示 -->
      <div v-if="!loading && filteredCouponList.length === 0" class="empty-tip">
        <el-empty description="暂无优惠券数据"></el-empty>
      </div>
    </el-card>

    <!-- 1. 新增优惠券对话框 -->
    <el-dialog
        v-model="showAddDialog"
        title="新增优惠券"
        width="600px"
        :close-on-click-modal="false"
        @open="handleAddDialogOpen"
    >
      <el-form
          :model="addCouponInfo"
          label-width="120px"
          class="coupon-form"
          :rules="couponRules"
          ref="addCouponFormRef"
      >
        <!-- 优惠券编号（自动生成可编辑） -->
        <el-form-item label="优惠券编号" prop="couponNo">
          <el-input
              v-model="addCouponInfo.couponNo"
              placeholder="自动生成（可修改）"
              maxlength="50"
          ></el-input>
        </el-form-item>
        <!-- 优惠券名称 -->
        <el-form-item label="优惠券名称" prop="name">
          <el-input
              v-model="addCouponInfo.name"
              placeholder="请输入优惠券名称"
              maxlength="100"
          ></el-input>
        </el-form-item>
        <!-- 优惠券类型（下拉选择） -->
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="addCouponInfo.type" placeholder="请选择类型">
            <el-option label="饮品兑换券" value="1"></el-option>
            <el-option label="满减券" value="2"></el-option>
            <el-option label="折扣券" value="3"></el-option>
            <el-option label="免单券" value="4"></el-option>
          </el-select>
        </el-form-item>
        <!-- 优惠值（根据类型显示不同提示） -->
        <el-form-item label="优惠值" prop="value">
          <el-input
              v-model="addCouponInfo.value"
              placeholder="满减券填金额，折扣券填折扣值（如8.8）"
              type="number"
              :min="addCouponInfo.type === 3 ? 0.1 : 0"
              :step="addCouponInfo.type === 3 ? 0.1 : 1"
          ></el-input>
          <div class="form-tip">
            {{ addCouponInfo.type === 2 ? '单位：元' : (addCouponInfo.type === 3 ? '单位：折（0.1~9.9）' : '无需填写') }}
          </div>
        </el-form-item>
        <!-- 最低消费 -->
        <el-form-item label="最低消费" prop="minSpend">
          <el-input
              v-model="addCouponInfo.minSpend"
              placeholder="0表示无门槛"
              type="number"
              min="0"
          ></el-input>
          <div class="form-tip">单位：元</div>
        </el-form-item>
        <!-- 适用商品范围 -->
        <el-form-item label="适用商品范围" prop="productScope">
          <el-select v-model="addCouponInfo.productScope" placeholder="请选择范围">
            <el-option label="全品类" value="ALL"></el-option>
            <el-option label="仅饮品" value="ALL_DRINK"></el-option>
            <el-option label="指定商品" value="CUSTOM"></el-option>
          </el-select>
          <el-input
              v-if="addCouponInfo.productScope === 'CUSTOM'"
              v-model="addCouponInfo.productIds"
              placeholder="指定商品ID，多个用逗号分隔"
              maxlength="500"
              style="margin-top: 10px;"
          ></el-input>
        </el-form-item>
        <!-- 有效期 -->
        <el-form-item label="有效期" prop="validStartTime">
          <el-date-picker
              v-model="addCouponInfo.validStartTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 48%; margin-right: 4%;"
          ></el-date-picker>
          <el-date-picker
              v-model="addCouponInfo.validEndTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 48%;"
          ></el-date-picker>
        </el-form-item>
        <!-- 库存设置 -->
        <el-form-item label="总发行量" prop="totalCount">
          <el-input
              v-model="addCouponInfo.totalCount"
              placeholder="请输入总发行量"
              type="number"
              min="1"
          ></el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="getLimit">
          <el-input
              v-model="addCouponInfo.getLimit"
              placeholder="每人最多领取数量"
              type="number"
              min="1"
              max="10"
          ></el-input>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item label="初始状态" prop="status">
          <el-select v-model="addCouponInfo.status" placeholder="请选择状态">
            <el-option label="可领取" value="1"></el-option>
            <el-option label="已下架" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="使用说明" prop="description">
          <el-input
              v-model="addCouponInfo.description"
              placeholder="请输入使用说明（用户可见）"
              maxlength="1000"
              type="textarea"
              rows="3"
          ></el-input>
        </el-form-item>
        <!-- 封面图 -->
        <el-form-item label="封面图">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8051/api/e/upload/img"
              :show-file-list="false"
              :on-success="(res) => handleImgUploadSuccess(res, 'add')"
              :before-upload="beforeImgUpload">
            <el-image
                v-if="addCouponInfo.coverImg"
                :src="addCouponInfo.coverImg"
                alt="优惠券封面图"
            ></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="form-tip">建议尺寸：200*200px，支持JPG/PNG格式</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="addCoupon">确定添加</el-button>
      </template>
    </el-dialog>

    <!-- 2. 编辑优惠券对话框 -->
    <el-dialog
        v-model="showEditDialog"
        title="编辑优惠券"
        width="600px"
        :close-on-click-modal="false"
        @open="handleEditDialogOpen"
    >
      <el-form
          :model="editCouponInfo"
          label-width="120px"
          class="coupon-form"
          :rules="couponRules"
          ref="editCouponFormRef"
      >
        <!-- 优惠券ID（禁用） -->
        <el-form-item label="优惠券ID" disabled>
          <el-input v-model="editCouponInfo.id" style="width: 100%;"></el-input>
        </el-form-item>
        <!-- 优惠券编号（禁用，避免修改） -->
        <el-form-item label="优惠券编号" disabled>
          <el-input v-model="editCouponInfo.couponNo" style="width: 100%;"></el-input>
        </el-form-item>
        <!-- 其余字段与新增一致，复用逻辑 -->
        <el-form-item label="优惠券名称" prop="name">
          <el-input
              v-model="editCouponInfo.name"
              placeholder="请输入优惠券名称"
              maxlength="100"
          ></el-input>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="editCouponInfo.type" placeholder="请选择类型" disabled>
            <el-option label="饮品兑换券" value="1"></el-option>
            <el-option label="满减券" value="2"></el-option>
            <el-option label="折扣券" value="3"></el-option>
            <el-option label="免单券" value="4"></el-option>
          </el-select>
          <div class="form-tip">类型一旦创建不可修改</div>
        </el-form-item>
        <el-form-item label="优惠值" prop="value">
          <el-input
              v-model="editCouponInfo.value"
              :placeholder="editCouponInfo.type === 2 ? '满减金额（元）' : (editCouponInfo.type === 3 ? '折扣值（如8.8）' : '无需填写')"
              type="number"
              :min="editCouponInfo.type === 3 ? 0.1 : 0"
              :step="editCouponInfo.type === 3 ? 0.1 : 1"
          ></el-input>
        </el-form-item>
        <el-form-item label="最低消费" prop="minSpend">
          <el-input
              v-model="editCouponInfo.minSpend"
              placeholder="0表示无门槛"
              type="number"
              min="0"
          ></el-input>
        </el-form-item>
        <el-form-item label="适用商品范围" prop="productScope">
          <el-select v-model="editCouponInfo.productScope" placeholder="请选择范围">
            <el-option label="全品类" value="ALL"></el-option>
            <el-option label="仅饮品" value="ALL_DRINK"></el-option>
            <el-option label="指定商品" value="CUSTOM"></el-option>
          </el-select>
          <el-input
              v-if="editCouponInfo.productScope === 'CUSTOM'"
              v-model="editCouponInfo.productIds"
              placeholder="指定商品ID，多个用逗号分隔"
              maxlength="500"
              style="margin-top: 10px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="有效期" prop="validStartTime">
          <el-date-picker
              v-model="editCouponInfo.validStartTime"
              type="datetime"
              placeholder="选择开始时间"
              style="width: 48%; margin-right: 4%;"
          ></el-date-picker>
          <el-date-picker
              v-model="editCouponInfo.validEndTime"
              type="datetime"
              placeholder="选择结束时间"
              style="width: 48%;"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="每人限领" prop="getLimit">
          <el-input
              v-model="editCouponInfo.getLimit"
              placeholder="每人最多领取数量"
              type="number"
              min="1"
              max="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editCouponInfo.status" placeholder="请选择状态">
            <el-option label="可领取" value="1"></el-option>
            <el-option label="已下架" value="0"></el-option>
            <el-option label="已领完" value="2" disabled></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
              v-model="editCouponInfo.description"
              placeholder="请输入使用说明（用户可见）"
              maxlength="1000"
              type="textarea"
              rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图">
          <el-upload
              class="avatar-uploader"
              action="/upload/img"
              :show-file-list="false"
              :on-success="(res) => handleImgUploadSuccess(res, 'edit')"
              :before-upload="beforeImgUpload"
          >
            <img v-if="editCouponInfo.coverImg" :src="editCouponInfo.coverImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="updateCoupon">确定保存</el-button>
      </template>
    </el-dialog>

    <!-- 3. 批量导入优惠券对话框 -->
    <el-dialog
        v-model="showBatchImportDialog"
        title="批量导入优惠券"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          :model="batchImportInfo"
          label-width="120px"
          class="coupon-form"
          ref="batchImportFormRef"
      >
        <el-form-item label="模板下载">
          <el-button
              type="text"
              @click="downloadImportTemplate"
              icon="el-icon-download"
              color="#409eff"
          >
            下载优惠券导入模板
          </el-button>
          <div class="form-tip">模板包含必填字段说明，请按格式填写</div>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
              class="upload-demo"
              action="/coupon/batch-import"
              :file-list="fileList"
              :before-upload="beforeFileUpload"
              :on-success="handleBatchImportSuccess"
              :on-error="handleBatchImportError"
              accept=".xlsx,.xls"
              :auto-upload="false"
              ref="uploadRef"
          >
            <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
            <el-button
                style="margin-left: 10px;"
                size="small"
                type="success"
                @click="submitBatchImport"
                :disabled="fileList.length === 0"
            >
              开始导入
            </el-button>
          </el-upload>
          <div class="form-tip">支持格式：Excel（.xlsx/.xls），单次最大100条</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchImportDialog = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 4. 删除确认对话框 -->
    <el-dialog
        v-model="showDeleteDialog"
        title="删除确认"
        width="300px"
        :close-on-click-modal="false"
    >
      <p>确定要删除该优惠券吗？</p>
      <p class="delete-warning" v-if="deleteCouponStockTips">
        <i class="el-icon-warning" style="color: #e6a23c;"></i>
        已发放的优惠券不允许删除，请先回收未使用的优惠券
      </p>
      <template #footer>
        <el-button @click="showDeleteDialog = false">取消</el-button>
        <el-button type="danger" @click="deleteCoupon" :disabled="deleteCouponStockTips">
          确定删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, reactive, watch, computed} from 'vue';
import {ElMessage, ElMessageBox, ElProgress, ElTag, ElUpload, ElDatePicker, ElSelect, ElOption} from 'element-plus';
import {Search, Upload2, Download, Plus} from '@element-plus/icons-vue';
import httpRequest from "@/config/request";

// ==================== 1. 状态管理 ====================
// 优惠券列表数据
const couponList = ref([]);
const filteredCouponList = ref([]);
const loading = ref(false);
const searchValue = ref('');

// 对话框状态
const showAddDialog = ref(false);
const showEditDialog = ref(false);
const showDeleteDialog = ref(false);
const showBatchImportDialog = ref(false);

// 表单引用
const addCouponFormRef = ref(null);
const editCouponFormRef = ref(null);
const batchImportFormRef = ref(null);
const uploadRef = ref(null);

// 删除相关状态
const deleteCouponId = ref('');
const deleteCouponStockTips = ref(false);

// 批量导入文件列表
const fileList = ref([]);

// ==================== 2. 表单数据 ====================
// 新增优惠券表单
const addCouponInfo = reactive({
  couponNo: '', // 自动生成
  name: '',
  type: 1, // 1-饮品兑换券，默认值
  value: 0,
  minSpend: 0,
  productScope: 'ALL', // ALL-全品类，默认值
  productIds: '',
  validStartTime: new Date(),
  validEndTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 默认7天后过期
  totalCount: 100,
  getLimit: 1,
  status: 1, // 1-可领取，默认值
  description: '',
  coverImg: null
});

// 编辑优惠券表单
const editCouponInfo = reactive({
  id: '',
  couponNo: '',
  name: '',
  type: 1,
  value: 0,
  minSpend: 0,
  productScope: 'ALL',
  productIds: '',
  validStartTime: '',
  validEndTime: '',
  totalCount: 0, // 已发放的优惠券不允许修改总发行量
  remainingCount: 0, // 只读
  getLimit: 1,
  status: 1,
  description: '',
  coverImg: null
});

// 批量导入表单
const batchImportInfo = reactive({
  file: null
});

// ==================== 3. 表单验证规则 ====================
const couponRules = reactive({
  name: [
    {required: true, message: '请输入优惠券名称', trigger: 'blur'},
    {max: 100, message: '优惠券名称最多100个字符', trigger: 'blur'}
  ],
  couponNo: [
    {required: true, message: '请输入优惠券编号', trigger: 'blur'},
    {max: 50, message: '优惠券编号最多50个字符', trigger: 'blur'}
  ],
  type: [
    {required: true, message: '请选择优惠券类型', trigger: 'change'}
  ],
  value: [
    {required: true, message: '请输入优惠值', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (addCouponInfo.type === 3 && (value < 0.1 || value > 9.9)) {
          callback(new Error('折扣值必须在0.1~9.9之间'));
        } else if ((addCouponInfo.type === 2 || addCouponInfo.type === 4) && value < 0) {
          callback(new Error('优惠值不能为负数'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  minSpend: [
    {required: true, message: '请输入最低消费', trigger: 'blur'},
    {min: 0, message: '最低消费不能为负数', trigger: 'blur'}
  ],
  validStartTime: [
    {required: true, message: '请选择开始时间', trigger: 'change'}
  ],
  validEndTime: [
    {required: true, message: '请选择结束时间', trigger: 'change'},
    {
      validator: (rule, value, callback) => {
        if (new Date(value) <= new Date(addCouponInfo.validStartTime)) {
          callback(new Error('结束时间必须晚于开始时间'));
        } else {
          callback();
        }
      }, trigger: 'change'
    }
  ],
  totalCount: [
    {required: true, message: '请输入总发行量', trigger: 'blur'},
    {min: 1, message: '总发行量至少为1', trigger: 'blur'}
  ],
  getLimit: [
    {required: true, message: '请输入每人限领数量', trigger: 'blur'},
    {min: 1, max: 10, message: '每人限领数量必须在1~10之间', trigger: 'blur'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ]
});

// ==================== 4. 核心方法 ====================
/**
 * 初始化：加载优惠券列表
 */
const getAllCoupons = async () => {
  try {
    loading.value = true;
    const res = await httpRequest.get('/coupon/list'); // 对应后端CouponController的GetList方法
    if (res.code === 200) {
      couponList.value = res.data || [];
      filteredCouponList.value = [...couponList.value];
      // 自动生成新增优惠券的编号（示例：COUPON+当前时间戳）
      addCouponInfo.couponNo = `COUPON${Date.now().toString().slice(-8)}`;
    } else {
      ElMessage.error(res.msg || '获取优惠券列表失败');
    }
  } catch (error) {
    console.error('获取优惠券列表失败', error);
    ElMessage.error('获取优惠券列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

/**
 * 搜索优惠券：按名称/编号模糊搜索
 */
const handleSearch = () => {
  const search = searchValue.value.trim().toLowerCase();
  filteredCouponList.value = couponList.value.filter(item =>
      (item.name && item.name.toLowerCase().includes(search)) ||
      (item.couponNo && item.couponNo.toLowerCase().includes(search))
  );
};

/**
 * 新增优惠券
 */
const addCoupon = async () => {
  try {
    // 表单验证
    const valid = await addCouponFormRef.value.validate();
    if (!valid) return;

    // 处理商品范围：指定商品时拼接ID，否则清空
    const productScope = addCouponInfo.productScope === 'CUSTOM'
        ? addCouponInfo.productIds
        : addCouponInfo.productScope;

    // 构造请求参数
    const params = {
      ...addCouponInfo,
      productScope // 覆盖原productScope
    };
    delete params.productIds; // 删除临时字段

    // 调用后端接口
    const res = await httpRequest.post('/coupon', params); // 对应后端Create方法
    if (res.code === 200) {
      ElMessage.success('优惠券新增成功');
      showAddDialog.value = false;
      // 重置表单
      addCouponInfo.name = '';
      addCouponInfo.value = 0;
      addCouponInfo.minSpend = 0;
      addCouponInfo.productScope = 'ALL';
      addCouponInfo.productIds = '';
      addCouponInfo.totalCount = 100;
      addCouponInfo.getLimit = 1;
      addCouponInfo.status = 1;
      addCouponInfo.description = '';
      addCouponInfo.coverImg = '';
      // 刷新列表
      await getAllCoupons();
    } else {
      ElMessage.error(res.msg || '优惠券新增失败');
    }
  } catch (error) {
    console.error('新增优惠券失败', error);
    ElMessage.error('新增优惠券失败，请重试');
  }
};

/**
 * 编辑优惠券：打开对话框时加载数据
 */
const editCoupon = (row) => {
  if (!row?.id) {
    ElMessage.warning('优惠券数据异常，请重试');
    return;
  }
  // 赋值到编辑表单
  editCouponInfo.id = row.id;
  editCouponInfo.couponNo = row.couponNo;
  editCouponInfo.name = row.name;
  editCouponInfo.type = row.type;
  editCouponInfo.value = row.value;
  editCouponInfo.minSpend = row.minSpend;
  editCouponInfo.productScope = row.productScope === 'ALL' || row.productScope === 'ALL_DRINK'
      ? row.productScope
      : 'CUSTOM';
  editCouponInfo.productIds = row.productScope === 'CUSTOM' ? row.productScope : '';
  editCouponInfo.validStartTime = new Date(row.validStartTime);
  editCouponInfo.validEndTime = new Date(row.validEndTime);
  editCouponInfo.totalCount = row.totalCount;
  editCouponInfo.remainingCount = row.remainingCount;
  editCouponInfo.getLimit = row.getLimit;
  editCouponInfo.status = row.status;
  editCouponInfo.description = row.description;
  editCouponInfo.coverImg = row.coverImg;
  // 打开对话框
  showEditDialog.value = true;
};

/**
 * 更新优惠券
 */
const updateCoupon = async () => {
  try {
    // 表单验证
    const valid = await editCouponFormRef.value.validate();
    if (!valid) return;

    // 处理商品范围
    const productScope = editCouponInfo.productScope === 'CUSTOM'
        ? editCouponInfo.productIds
        : editCouponInfo.productScope;

    // 构造请求参数（排除不可修改字段）
    const params = {
      ...editCouponInfo,
      productScope
    };
    delete params.productIds;
    delete params.remainingCount; // 剩余数量由后端维护

    // 调用后端接口
    const res = await httpRequest.put('/coupon', params); // 对应后端Update方法
    if (res.code === 200) {
      ElMessage.success('优惠券更新成功');
      showEditDialog.value = false;
      // 刷新列表
      await getAllCoupons();
    } else {
      ElMessage.error(res.msg || '优惠券更新失败');
    }
  } catch (error) {
    console.error('更新优惠券失败', error);
    ElMessage.error('更新优惠券失败，请重试');
  }
};

/**
 * 删除优惠券：打开确认对话框
 */
const handleDeleteConfirm = (id) => {
  const coupon = couponList.value.find(item => item.id === id);
  // 校验：已发放的优惠券不允许删除
  deleteCouponStockTips.value = coupon.totalCount > coupon.remainingCount;
  deleteCouponId.value = id;
  showDeleteDialog.value = true;
};

/**
 * 执行删除优惠券
 */
const deleteCoupon = async () => {
  try {
    const res = await httpRequest.delete(`/coupon/${deleteCouponId.value}`); // 对应后端Delete方法
    if (res.code === 200) {
      ElMessage.success('优惠券删除成功');
      showDeleteDialog.value = false;
      // 刷新列表
      await getAllCoupons();
    } else {
      ElMessage.error(res.msg || '优惠券删除失败');
    }
  } catch (error) {
    console.error('删除优惠券失败', error);
    ElMessage.error('删除优惠券失败，请重试');
  }
};

/**
 * 批量导入：下载模板
 */
const downloadImportTemplate = () => {
  // 调用后端下载接口
  window.open('/coupon/export-template', '_blank');
  ElMessage.success('模板下载中，请稍候');
};

/**
 * 批量导入：提交上传
 */
const submitBatchImport = () => {
  uploadRef.value.submit();
};

/**
 * 批量导入：文件上传前校验
 */
const beforeFileUpload = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
      file.type === 'application/vnd.ms-excel';
  const isLt1M = file.size / 1024 / 1024 < 1; // 限制1MB以内

  if (!isExcel) {
    ElMessage.error('请上传Excel格式的文件（.xlsx/.xls）');
    return false;
  }
  if (!isLt1M) {
    ElMessage.error('上传文件大小不能超过1MB');
    return false;
  }
  return true;
};

/**
 * 批量导入：上传成功回调
 */
const handleBatchImportSuccess = (res) => {
  if (res.code === 200) {
    ElMessage.success(`批量导入成功，共导入${res.data.successCount}条，失败${res.data.failCount}条`);
    // 若有失败数据，提供下载失败日志
    if (res.data.failCount > 0 && res.data.failLogUrl) {
      ElMessageBox.confirm(
          '部分数据导入失败，是否下载失败日志？',
          '提示',
          {
            confirmButtonText: '下载',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        window.open(res.data.failLogUrl, '_blank');
      });
    }
    // 重置状态
    showBatchImportDialog.value = false;
    fileList.value = [];
    // 刷新列表
    getAllCoupons();
  } else {
    ElMessage.error(res.msg || '批量导入失败');
  }
};

/**
 * 批量导入：上传失败回调
 */
const handleBatchImportError = () => {
  ElMessage.error('文件上传失败，请检查网络后重试');
};

/**
 * 图片上传成功回调
 */
const handleImgUploadSuccess = (res, type = 'add') => {
  if (res.code === 200) {
    const imgUrl = res.data;
    if (type === 'add') {
      addCouponInfo.coverImg = imgUrl;
    } else {
      editCouponInfo.coverImg = imgUrl;
    }
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(res.msg || '图片上传失败');
  }
};

/**
 * 图片上传前校验
 */
const beforeImgUpload = (file) => {
  const isImage = file.type.startsWith('image/');

  if (!isImage) {
    ElMessage.error('请上传图片格式的文件（JPG/PNG）');
    return false;
  }
  return true;
};

// ==================== 5. 辅助方法 ====================
/**
 * 表格行点击事件（可选：添加选中效果）
 */
const handleRowClick = (row) => {
  // 可添加行选中逻辑，如：
  // couponList.value.forEach(item => item.isSelected = item.id === row.id);
};
/**
 * 格式化日期
 */
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};
/**
 * 打开新增对话框：重置表单
 */
const handleAddDialogOpen = () => {
  if (addCouponFormRef.value) {
    addCouponFormRef.value.resetFields();
  }
  // 重置默认值
  addCouponInfo.validStartTime = new Date();
  addCouponInfo.validEndTime = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
  addCouponInfo.couponNo = `COUPON${Date.now().toString().slice(-8)}`;
};

/**
 * 打开编辑对话框：无需额外处理（数据已在editCoupon中赋值）
 */
const handleEditDialogOpen = () => {
};

/**
 * 优惠券类型名称转换（字典映射）
 */
const getCouponTypeName = (type) => {
  const typeMap = {
    1: '饮品兑换券',
    2: '满减券',
    3: '折扣券',
    4: '免单券'
  };
  return typeMap[type] || '未知类型';
};

/**
 * 优惠券类型标签样式（若依风格：不同类型不同颜色）
 */
const getCouponTypeTagType = (type) => {
  const typeMap = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'danger'
  };
  return typeMap[type] || 'default';
};

/**
 * 优惠券状态名称转换（字典映射）
 */
const getCouponStatusName = (status) => {
  const statusMap = {
    0: '已下架',
    1: '可领取',
    2: '已领完'
  };
  return statusMap[status] || '未知状态';
};

// ==================== 6. 监听与初始化 ====================
// 监听搜索值变化，实时搜索
watch(searchValue, (newVal) => {
  handleSearch();
});

// 页面初始化加载数据
onMounted(async () => {
  await getAllCoupons();
});
</script>

<style scoped>
/* 基础容器样式（若依风格：浅灰背景+固定内边距） */
.coupon-manage-container {
  padding: 20px;
  background-color: #f5f6f8;
  min-height: calc(100vh - 110px);
  overflow: visible;
}

/* 页面标题栏（若依风格：标题+按钮横向排列） */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin: 0;
}

.operation-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 表格卡片（若依风格：白色背景+轻微阴影） */
.table-card {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  padding: 15px;
  background-color: #fff;
}

/* 空数据提示（若依风格：居中+padding） */
.empty-tip {
  padding: 50px 0;
  text-align: center;
}

/* 表单样式（若依风格：标签右对齐+间距） */
.coupon-form {
  margin-top: 20px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  line-height: 1.5;
}

/* 封面图上传样式 */
.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 24px;
  color: #c0c4cc;
  background-color: #f5f7fa;
  width: 100px;
  height: 100px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
}

/* 库存文本样式 */
.stock-text {
  font-size: 12px;
  color: #999;
  text-align: center;
  margin-top: 4px;
}

/* 删除警告样式 */
.delete-warning {
  color: #e6a23c;
  margin-top: 10px;
  line-height: 1.5;
}

/* 对话框底部按钮样式（若依风格：右对齐+间距） */
.el-dialog__footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>